//
//  UIView+LoadingOrBlank.m
//  FlagForiOS
//
//  Created by 容贤郁 on 2016/12/10.
//  Copyright © 2016年 Minidai. All rights reserved.
//

#import "UIView+LoadingOrBlank.h"
#import <objc/runtime.h>

#define MyBackgroundColor [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0]

@implementation UIView (LoadingOrBlank)

static char LoadingViewKey,BlankPageViewKey;

- (void)configBlankPage:(SYBlankPageType)blankPageType hasData:(BOOL)hasData  reloadButtonBlock:(void(^)(id sender))block
{
    if([self.loadingView isLoading]){
        [self.loadingView stopAnimating];
    }
    
    if (hasData) {
        if (self.blankPageView)
        {
            self.blankPageView.hidden = YES;
            [self.blankPageView removeFromSuperview];
        }
    }
    else
    {
        if (!self.blankPageView)
        {
            self.blankPageView = [[SYBlankPageView alloc] initWithFrame:self.bounds];
        }
        self.blankPageView.hidden = NO;
        [self.blankPageContainer addSubview:self.blankPageView];
        
        [self.blankPageView configWithType:blankPageType hasData:NO reloadButtonBlock:block];
        
    }
}

- (SYBlankPageType)blankPageTypeWithError:(NSError *)error {
    SYBlankPageType errorType = SYBlankPageTypeError;
    switch (error.code) {
        case NSURLErrorTimedOut:
            errorType = SYBlankPageTypeTimeOut;
            break;
        
        case NSURLErrorNotConnectedToInternet:
        case NSURLErrorNetworkConnectionLost:
            errorType = SYBlankPageTypeNetworkLost;
            break;
            
        case NSURLErrorCannotConnectToHost:
            errorType = SYBlankPageTypeCannotConnectToServer;
            break;
            
        case NSURLErrorBadServerResponse:
            errorType = SYBlankPageTypeServerError;
            break;
        default:
            
//            errorType = SYBlankPageTypeError;
            break;
    }
    
    return errorType;
}
#pragma mark   LoadingView  Runtime 动态绑定
- (void)setLoadingView:(SYLoadingView *)loadingView
{
    [self willChangeValueForKey:@"LoadingViewKey"];
    objc_setAssociatedObject(self, &LoadingViewKey,
                             loadingView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"LoadingViewKey"];
}

- (SYLoadingView *)loadingView {
    return objc_getAssociatedObject(self, &LoadingViewKey);
}

#pragma mark   LoadingView  Runtime 动态绑定

- (void)setBlankPageView:(SYBlankPageView *)pageView {
    [self willChangeValueForKey:@"BlankPageViewKey"];
    objc_setAssociatedObject(self, &BlankPageViewKey,
                             pageView,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self didChangeValueForKey:@"BlankPageViewKey"];
}

- (SYBlankPageView *)blankPageView {
    return objc_getAssociatedObject(self, &BlankPageViewKey);
}

- (void)beginLoading {
    for (UIView *aView in [self.blankPageContainer subviews]) {
        if ([aView isKindOfClass:[SYBlankPageView class]] && !aView.hidden) {
            return;
        }
    }
    
    if (!self.loadingView) { //初始化LoadingView
        self.loadingView = [[SYLoadingView alloc] initWithFrame:self.bounds];
    }
    [self addSubview:self.loadingView];
    
    [self.loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.self.edges.equalTo(self);
    }];
    
    for (id subview in self.subviews) {
        if ([subview isKindOfClass:[UITableView class]]) {
            NSLog(@"fram: %@", subview);
        }
    }
    [self.loadingView startAnimating];
}

- (void)endLoading{
    if (self.loadingView) {
        [self.loadingView stopAnimating];
    }
}

- (UIView *)blankPageContainer {
    UIView *blankPageContainer = self;
    for (UIView *aView in [self subviews]) {
        if ([aView isKindOfClass:[UITableView class]]) {
            blankPageContainer = aView;
        }
    }
    return blankPageContainer;
}

@end

#pragma mark - SYLoadingView @implementation

@interface SYLoadingView ()

@property (nonatomic, assign) CGFloat loopAngle, monkeyAlpha, angleStep, alphaStep;

@end

@implementation SYLoadingView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = MyBackgroundColor;
        NSMutableArray *gifImageArray = [NSMutableArray array];
        for (NSInteger i = 1; i <= 21; i++) {
            UIImage *gifImage = [UIImage imageNamed:[NSString stringWithFormat:@"loading_%zd", i]];
            [gifImageArray addObject:gifImage];
        }
        UIImage *loadingImg = gifImageArray.firstObject;
        self.loopView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, loadingImg.size.width, loadingImg.size.height)];
        self.loopView.animationImages = gifImageArray;
        self.loopView.animationRepeatCount = 0;
        self.loopView.animationDuration = 0.6;
        
        self.monkeyView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
//        [_loopView setCenter:self.center];
        [self.monkeyView setCenter:self.center];
        
        UILabel *loadingLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        loadingLabel.text = @"努力加载中...";
        loadingLabel.textColor = [UIColor colorWithRed:153/255.0 green:153/255.0 blue:153/255.0 alpha:1.0];
        loadingLabel.font = [UIFont systemFontOfSize:13.0];
        
        [self addSubview:self.loopView];
        [self addSubview:self.monkeyView];
        [self addSubview:loadingLabel];

        
        [self.monkeyView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.centerY.equalTo(self);
        }];
        
        
        [self.loopView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            if (kScreenWidth <= 320) {
                make.bottom.equalTo(self.mas_centerY).offset(30);
            } else {
                make.bottom.equalTo(self.mas_centerY).offset(-20);
            }
            
        }];
        
        __weak __typeof(self)weakSelf = self;
        
        [loadingLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.loopView.mas_bottom).offset(10.0);
            make.centerX.equalTo(weakSelf.loopView);
        }];
        self.loopAngle = 0.0;
        self.monkeyAlpha = 1.0;
        self.angleStep = 360/4;
        self.alphaStep = 1.0/3.0;
    }
    return self;
}

- (void)startAnimating {
    self.hidden = NO;
    if (self.isLoading) {
        return;
    }
    _isLoading = YES;
    [self loadingAnimation];
}

- (void)stopAnimating{
    self.hidden = YES;
    _isLoading = NO;
    [self.loopView stopAnimating];
    [self removeFromSuperview];
}

- (void)loadingAnimation{
//    static CGFloat duration = 0.4f;
    
    _loopAngle += _angleStep;
    if (_monkeyAlpha >= 1.0 || _monkeyAlpha <= 0.0) {
        _alphaStep = -_alphaStep;
    }
    _monkeyAlpha += _alphaStep;
    [_loopView startAnimating];
//    [UIView animateWithDuration:duration delay:0.0 options:UIViewAnimationOptionCurveLinear animations:^{
//        CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(_loopAngle * (M_PI / 180.0f));
//        _loopView.transform = loopAngleTransform;
//        _monkeyView.alpha = _monkeyAlpha;
//    } completion:^(BOOL finished)
//     {
//         if (_isLoading && [self superview] != nil)
//         {
//             [self loadingAnimation];
//         }
//         else
//         {
//             [self removeFromSuperview];
//             
//             _loopAngle = 0.0;
//             _monkeyAlpha = 1,0;
//             _alphaStep = ABS(_alphaStep);
//             CGAffineTransform loopAngleTransform = CGAffineTransformMakeRotation(_loopAngle * (M_PI / 180.0f));
//             _loopView.transform = loopAngleTransform;
//             _monkeyView.alpha = _monkeyAlpha;
//         }
//     }];
}
@end

#pragma mark - SYBlankPageView @implementation
@implementation SYBlankPageView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = MyBackgroundColor;
    }
    return self;
}
- (void)configWithType:(SYBlankPageType)blankPageType hasData:(BOOL)hasData reloadButtonBlock:(void (^)(id))block{
    
    if (hasData)
    {
        [self removeFromSuperview];
        return;
    }
    self.alpha = 1.0;
    // 图片
    if (!_imgView) {
        _imgView = [[UIImageView alloc] initWithFrame:CGRectZero];
        [self addSubview:_imgView];
    }
    // 文字
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _tipLabel.backgroundColor = [UIColor clearColor];
        _tipLabel.numberOfLines = 0;
        _tipLabel.font = [UIFont systemFontOfSize:15];
        _tipLabel.textColor = [UIColor lightGrayColor];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_tipLabel];
    }
    
    if (!_investButton) {
        _investButton = [[UIButton alloc]initWithFrame:CGRectZero];
        _investButton.hidden = YES;
        [_investButton setTitle:@"去出借" forState:UIControlStateNormal];
        [_investButton setBackgroundImage:[UIImage imageNamed:@"finance_invest_btn"] forState:UIControlStateNormal];
        _investButton.titleLabel.font = [UIFont systemFontOfSize:15];
//        _investButton.backgroundColor = [UIColor redColor];
        [_investButton addTarget:self action:@selector(investAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_investButton];
    }
    __weak __typeof(self)weakSelf = self;
    // 布局
    [_tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.centerX.equalTo(self);
        CGRect screenBounds = [UIScreen mainScreen].bounds;
        if (self.bounds.size.height < screenBounds.size.height) {
            make.bottom.equalTo(self.mas_centerY).offset(-10);
        } else {
            if (screenBounds.size.width <= 320) {
                make.bottom.equalTo(self.mas_centerY).offset(-30);
            } else {
                make.bottom.equalTo(self.mas_centerY).offset(-60);
            }
        }
        make.centerX.equalTo(self);
        make.top.equalTo(weakSelf.imgView.mas_bottom).offset(10);
        make.height.mas_equalTo(50);
    }];
    [_imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        
    }];
    
    [_investButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self);
        make.top.equalTo(weakSelf.tipLabel.mas_bottom).mas_offset(20);
//        make.left.equalTo(self).mas_offset(60);
        make.width.equalTo(self).multipliedBy(0.7);
        make.height.mas_equalTo(40);
        
    }];
    _investButton.layer.cornerRadius = 20;
    _investButton.clipsToBounds = YES;
    
    // 空白数据
    if (block) {
        _reloadButtonBlock  =[block copy];
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(reloadButtonClicked:)]];
        self.userInteractionEnabled = YES;
    }
    NSString *imageName, *tipStr;
    switch (blankPageType) {
        case SYBlankPageTypeNoData:
        {
            imageName = @"blankpage_emptydata";
            tipStr = @"哎呀~这里空空如也~";
        }
            break;
        case SYBlankPageTypeError:
        {
            imageName = @"blankpage_error";
            tipStr = @"哎呀~出错了\n点击屏幕，重新加载";
        }
            break;
        case SYBlankPageTypeNetworkError:
        {
            imageName = @"blankpage_neterror";
            tipStr = @"哎呀~网络好像出了点问题\n点击屏幕，重新加载";
        }
            break;
        case SYBlankPageTypeTimeOut:
        {
            imageName = @"blankpage_neterror";
            tipStr = @"哎呀~请求超时了\n点击屏幕，重新加载";
        }
            break;
            
        case SYBlankPageTypeNetworkLost:
        {
            imageName = @"blankpage_neterror";
            tipStr = @"哎呀~网络被UFO劫走了\n点击屏幕，重新加载";
        }
            break;
        case SYBlankPageTypeServerError:
        {
            imageName = @"blankpage_neterror";
            tipStr = @"哎呀~服务器出了点问题\n点击屏幕，重新加载";
        }
            break;
        case SYBlankPageTypeCannotConnectToServer:
        {
            imageName = @"blankpage_neterror";
            tipStr = @"哎呀~无法连接服务器\n点击屏幕，重新加载";
        }
            break;
        case SYBlankPageTypeNoCoupon:
        {
            imageName = @"blankpage_empty_coupon";
            tipStr = @"哎呀~您还没有赠利券哦";
        }
            break;
        case SYBlankPageTypeNoComment:
        {
            imageName = @"blankpage_emptydata";
            tipStr = @"暂无评论~";
        }
            break;
        case SYBlankPageTypeNoMessage:
        {
            imageName = @"blankpage_emptydata";
            tipStr = @"暂无消息~";
        }
            break;
            
        default://其它页面（这里没有提到的页面，都属于其它）
        {
            imageName = @"blankpage_emptydata";
            tipStr = @"这里还什么都没有~";
        }
            break;
    }
    [_imgView setImage:[UIImage imageNamed:imageName]];
    _tipLabel.text = tipStr;
    
    
}
- (void)reloadButtonClicked:(id)sender{
    self.hidden = YES;
    [self removeFromSuperview];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.reloadButtonBlock) {
            self.reloadButtonBlock(sender);
        }
    });
}

#pragma mark - 投资按钮
- (void)investAction:(UIButton*)sender{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"goInvestButtonAction" object:nil];
}
@end
